//
//  ChatRoomCell.m
//  MooreDoll
//
//  Created by Joe on 2014/12/4.
//  Copyright (c) 2014年 Tank. All rights reserved.
//

#import "MessageRoomCell.h"
#import "AppDelegate.h"

@implementation MessageRoomCell
@synthesize LB_lastMessage,LB_update,LB_roomName,IV_roomIcon;

- (void)awakeFromNib {
    // Initialization code
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

-(void)setCellByChatRoom:(ChatRoom *)room{
    
    
    //拿取該聊天室之最後一次更新的資訊
    NSManagedObjectContext *managedObjectContext = ((AppDelegate *)[UIApplication sharedApplication].delegate).managedObjectContext;
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@" content.owner == %@  ",room.owner];
    NSFetchRequest *fetch = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"ChatMessage" inManagedObjectContext:managedObjectContext];
    fetch.fetchLimit = 1;
    fetch.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"update" ascending:NO]];
    [fetch setPredicate:predicate];
    [fetch setEntity:entity];
    ChatMessage *lastChatRecord = [managedObjectContext executeFetchRequest:fetch error:nil].lastObject;
    
    //取得最後一筆資訊後，assign應有的資訊給cell顯示
    LB_roomName.text = room.displayName;
    if ([lastChatRecord.audioPath isEqualToString:@""])
        LB_lastMessage.text = lastChatRecord.message;
    else
        LB_lastMessage.text = lastChatRecord.audioPath;
    
    //最後時間assign
    NSDateFormatter *dateFormate = [[NSDateFormatter alloc] init];
    [dateFormate setDateFormat:@"HH:mm"];
    NSString *dateString = [dateFormate stringFromDate:lastChatRecord.update];
    LB_update.text = dateString;
    
    //取得該聊天室的擁有者
    NSFetchRequest *fetchRoster = [[NSFetchRequest alloc] init];
    NSPredicate *predicateRoster = [NSPredicate predicateWithFormat:@"jid == %@",room.owner];
    NSEntityDescription *entityRoster = [NSEntityDescription entityForName:@"Roster" inManagedObjectContext:managedObjectContext];
    [fetchRoster setPredicate:predicateRoster];
    [fetchRoster setEntity:entityRoster];
    fetchRoster.fetchLimit = 1;
    Roster *roomOwner = [managedObjectContext executeFetchRequest:fetchRoster error:nil].lastObject;
    
    //assign userPhoto
//    if (roomOwner.photoPath!=nil && ![roomOwner.photoPath isEqualToString:@""])
//    {
//        NSData *userImgData = [[NSData alloc] initWithContentsOfURL:[[NSURL alloc] initWithString:roomOwner.photoPath]];
//        if (userImgData!=nil)
//        {
//            UIImage *userImg = [[UIImage alloc] initWithData:userImgData];
//            [IV_roomIcon setImage:userImg];
//        }
//
//    }
//    else
//    {
        [IV_roomIcon setImage:[UIImage imageNamed:@"dficon_user"]];
//    }
    
    //assign room做備份
    self.chatRoom = room;
}

@end
